function Promise(executor) {
  // 状态描述
  this.state = 'pending'
  // 成功结果
  this.value = undefined
  // 失败原因
  this.reason = undefined

  // 保存成功回调
  this.onResolvedCallbacks = []
  // 保存失败回调
  this.onRejectedCallbacks = []

  let _this = this

  // 让处理器函数立即执行
  try {
    executor(resolve, reject)
  } catch (err) {
    reject(err)
  }

  function resolve(value) {
    if (_this.state === 'pending') {
      _this.value = value
      // 遍历执行成功回调
      _this.onResolvedCallbacks.map(cb => cb(value))
      _this.state = 'resolved'
    }
  }

  function reject(reason) {
    if (_this.state === 'pending') {
      _this.value = reason
      // 遍历执行失败回调
      _this.onRejectedCallbacks.map(cb => cb(reason))
      _this.state = 'rejected'
    }
  }
  /**
   * 解析then返回值与新Promise对象
   * @param {Object} 新的Promise对象，就是我们创建的promise2实例
   * @param {*} x 上一个then的返回值
   * @param {Function} resolve promise2处理器函数的resolve
   * @param {Function} reject promise2处理器函数的reject
   */
  function resolvePromise(promise2, x, resolve, reject) {
    if (promise2 === x) {
      reject(new TypeError('请避免Promise循环引用'))
    }
  }
}

Promise.prototype.then = function(onFulfiled, onRejected) {
  // 回调参数不为函数时 变成回调函数返回普通值
  onFulfiled = typeof onFulfiled === 'function' ? onFulfiled : value => value
  onRejected = typeof onRejected === 'function' ? onRejected : err => { throw err }

  let promise2 = new Promise((resolve, reject) => {
    if (this.state === 'pending') {
      this.onResolvedCallbacks.push(() => {
        try {
          let x = onFulfilled(this.value)
          resolve(x)
        } catch (e) {
          reject(e)
        }
      })
      this.onRejectedCallbacks.push(() => {
        try {
          let x = onRejected(this.value)
          resolve(x)
        } catch (e) {
          reject(e)
        }
      })
    }
  
    if (this.state === 'resolved') {
      try {
        let val = onFulfiled(this.value)
        resolve(val)        
      } catch (e) {
        reject(e)
      }
    }
    if (this.state === 'rejected') {
      try {
        let val = onRejected(this.reason)
        resolve(val)        
      } catch (e) {
        reject(e)
      }
    }
  })
  
  return promise2
}

new Promise((resolve, reject) => {
  console.log(1)  
  resolve(2)
  console.log(3)
}).then(data => {
  console.log(data)
})
